﻿#include "tcpclient.h"
#include <QThread>
TcpClient::TcpClient(QObject *parent) : QTcpSocket{parent} {
    setSocketOption(QAbstractSocket::KeepAliveOption, 1);
    connect(this, &QAbstractSocket::connected, this, &TcpClient::slot_connected);
    connect(this, &QIODevice::readyRead, this, &TcpClient::slot_readData);
    connect(this, &QAbstractSocket::disconnected, this, &TcpClient::slot_disconnected);
}

TcpClient::~TcpClient() {
    disconnect();
    abort();
}

bool TcpClient::connectHost(const QString &ip, int port) {
    disconnect();
    connectToHost(ip, port);
    if (waitForConnected(3000)) {
        return true;
    }
    return false;
}

bool TcpClient::disconnect() {
    disconnectFromHost();
    if (state() == QAbstractSocket::UnconnectedState || waitForDisconnected(1000)) {
        return true;
    }
    return false;
}

bool TcpClient::isConnected() {
    return (state() == QAbstractSocket::ConnectedState);
}

void TcpClient::accepted(qintptr sockDesc) {
    disconnect();
    setSocketDescriptor(sockDesc);
    emit QAbstractSocket::connected();
}

int TcpClient::send(const QByteArray &data) {
    int size = -1;
    if (isConnected()) {
        size = write(data);
        flush();
    }
    //QThread::msleep(100);
    return size;
}

void TcpClient::onReceived(const QByteArray &data) {

    QString buf = data;
    emit readbuf(buf);
}

//private slots:
void TcpClient::slot_connected() {
    onConnected();
}

void TcpClient::slot_readData() {
    onReceived(readAll());
}

void TcpClient::slot_disconnected() {
    onDisconnected();
}


